package com.yhou.sharding.utils;

/**
 * @author houyong
 * @ProjectName sharding_demo
 * @Description:
 * @date 2018/11/16 下午2:56
 */
public class IdUtil {
    public IdUtil() {
    }

    public static void main(String[] srgs) {
        System.out.println(getLastNumber("074", 6));
        System.out.println(getFirstNumber("74534535", 5));
    }

    public static int getNumByLength(int length) {
        if (length < 10 && length >= 1) {
            int mid = (int) Math.pow(10.0D, (double) (length - 1));
            return (int) (Math.random() * 9.0D * (double) mid) + mid;
        } else {
            throw new RuntimeException("最大支持1-9位长度的随机数生成");
        }
    }

    /**
     * @deprecated
     */
    @Deprecated
    public static String getLastNumber(long id, int length) {
        String idStr = String.valueOf(id);
        int size = Math.min(idStr.length(), length);
        idStr = idStr.substring(idStr.length() - size);
        return String.format("%0" + length + "d", Long.valueOf(idStr));
    }

    public static String getLastNumber(String idStr, int length) {
        int size = Math.min(idStr.length(), length);
        idStr = idStr.substring(idStr.length() - size);
        return String.format("%0" + length + "d", Long.valueOf(idStr));
    }

    /**
     * @deprecated
     */
    @Deprecated
    public static String getFirstNumber(long id, int length) {
        String idStr = String.valueOf(id);
        if (length > idStr.length()) {
            throw new RuntimeException("截取长度超过总长度");
        } else {
            idStr = idStr.substring(0, length);
            return String.format("%0" + length + "d", Long.valueOf(idStr));
        }
    }

    public static String getFirstNumber(String idStr, int length) {
        if (length > idStr.length()) {
            throw new RuntimeException("截取长度超过总长度");
        } else {
            idStr = idStr.substring(0, length);
            return String.format("%0" + length + "d", Long.valueOf(idStr));
        }
    }
}
